package com.ekuaitu.kuaitu.activity;

import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.base.BaseActivity;
import com.ekuaitu.kuaitu.bean.BaseBean;
import com.ekuaitu.kuaitu.bean.GetRemindBean;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.KuaituDialog;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.SetRemindTimeDialog;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by jieyaozu on 2017/5/16.
 */

public class CarNetSystemActivity extends BaseActivity implements View.OnClickListener {
    private PullToRefreshListView refreshListView;
    private ImageView ivReturn;
    private ListView mListView;
    private ListViewAdapter listViewAdapter;
    //private TextView tvSelectAll;
    private TextView tvRemind, tvCancelRemind;
    private LinearLayout progressBar_activity;
    private int currentIndex = 1;
    private String latitude;
    private String longitude;
    private List<GetRemindBean.Attachment.RemindPark> remindParkList = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.activity_carsystem;
    }

    @Override
    public void initView() {
        latitude = getIntent().getStringExtra(IntentKey.INTENT_LATITUDE);
        longitude = getIntent().getStringExtra(IntentKey.INTENT_LONGITUDE);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimaryWhite), 0, true);
        ivReturn = (ImageView) findViewById(R.id.carsystem_ivReturn);
        progressBar_activity = (LinearLayout) findViewById(R.id.progressBar_activity);
        refreshListView = (PullToRefreshListView) findViewById(R.id.refresh_listview);
        refreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        mListView = refreshListView.getRefreshableView();
        //tvSelectAll = (TextView) findViewById(R.id.carsystem_selectall);
        tvRemind = (TextView) findViewById(R.id.carsystem_remind_button);
        tvCancelRemind = (TextView) findViewById(R.id.carsystem_cancel_remind);
        listViewAdapter = new ListViewAdapter();
        mListView.setAdapter(listViewAdapter);

        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                refreshListView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshListView.onRefreshComplete();
                    }
                }, 500);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                currentIndex++;
                loadData(currentIndex);
            }
        });

        ivReturn.setOnClickListener(this);
        //tvSelectAll.setOnClickListener(this);
        tvRemind.setOnClickListener(this);
        tvCancelRemind.setOnClickListener(this);
        loadData(currentIndex);
    }

    private void loadData(int pageIndex) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getRemind(MyApplication.getInstance().getRequestFieldMap(),latitude, longitude, pageIndex + "", "15").enqueue(new Callback<GetRemindBean>() {
            @Override
            public void onResponse(Call<GetRemindBean> call, Response<GetRemindBean> response) {
                refreshListView.onRefreshComplete();
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        GetRemindBean.Attachment attachment = response.body().getAttachment();
                        if (attachment != null) {
                            List<GetRemindBean.Attachment.RemindPark> recordedBeanList = attachment.getParkList();
                            if (recordedBeanList != null) {
                                remindParkList.addAll(recordedBeanList);
                                listViewAdapter.notifyDataSetChanged();
//                                if (isAllSelected()) {
//                                    tvSelectAll.setText("取消全选");
//                                } else {
//                                    tvSelectAll.setText("全选");
//                                }
                            }
                            int remindStatus = attachment.getRemindStatus();
                            if (remindStatus == 0) {
                                tvCancelRemind.setBackgroundResource(R.drawable.corner_background_gray);
                                tvCancelRemind.setTextColor(getResources().getColor(R.color.gray3));
                                tvCancelRemind.setClickable(false);
                            } else {
                                tvCancelRemind.setBackgroundResource(R.drawable.selector_button_bg_yellow);
                                tvCancelRemind.setTextColor(getResources().getColor(R.color.white));
                                tvCancelRemind.setClickable(true);
                            }
                        }
                    } else {
                        ToastCompat.makeText(CarNetSystemActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<GetRemindBean> call, Throwable t) {
                refreshListView.onRefreshComplete();
            }
        });
    }

    /**
     * 设置提醒
     *
     * @param parkIdStr    网点id
     * @param remindMinute 有车提醒有效时间（分钟）
     */
    private void requestSaveRemind(String parkIdStr, int remindMinute) {
        progressBar_activity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).saveRemind(MyApplication.getInstance().getRequestFieldMap(),parkIdStr, remindMinute, 1).enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                progressBar_activity.setVisibility(View.GONE);
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        ToastCompat.makeText(CarNetSystemActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        tvCancelRemind.setBackgroundResource(R.drawable.selector_button_bg_yellow);
                        tvCancelRemind.setTextColor(getResources().getColor(R.color.white));
                        tvCancelRemind.setClickable(true);
                        Constants.isSaveRemind = true;
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                progressBar_activity.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 取消提醒
     */
    private void requestCancelRemind() {
        progressBar_activity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).cancelRemind(MyApplication.getInstance().getRequestFieldMap()).enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                progressBar_activity.setVisibility(View.GONE);
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        ToastCompat.makeText(CarNetSystemActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        tvCancelRemind.setBackgroundResource(R.drawable.corner_background_gray);
                        tvCancelRemind.setTextColor(getResources().getColor(R.color.gray3));
                        tvCancelRemind.setClickable(false);
                        Constants.isCancelRemind = true;
                        for (int i = 0; i < remindParkList.size(); i++) {
                            remindParkList.get(i).setRemindStatus(0);
                        }
                        listViewAdapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                progressBar_activity.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.carsystem_ivReturn:
                finish();
                break;
            case R.id.carsystem_selectall:
//                if (!isAllSelected()) {
//                    tvSelectAll.setText("取消全选");
//                    for (int i = 0; i < remindParkList.size(); i++) {
//                        remindParkList.get(i).setRemindStatus(1);
//                    }
//                } else {
//                    tvSelectAll.setText("全选");
//                    for (int i = 0; i < remindParkList.size(); i++) {
//                        remindParkList.get(i).setRemindStatus(0);
//                    }
//                }
//                listViewAdapter.notifyDataSetChanged();
                break;
            case R.id.carsystem_remind_button:
                if (getSelectedCount() <= 0) {
                    ToastCompat.makeText(CarNetSystemActivity.this, "请至少选择一个网点", Toast.LENGTH_SHORT).show();
                    return;
                }
                final SetRemindTimeDialog dialog = new SetRemindTimeDialog(this);
                dialog.setYesOnclickListener("确定", new SetRemindTimeDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        if (TextUtils.isEmpty(dialog.getSelectRadioButton())) {
                            ToastCompat.makeText(CarNetSystemActivity.this, "请选择一个有效时间", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        String parkIdStrs = getSelectedParkIds();
                        requestSaveRemind(parkIdStrs, Integer.parseInt(dialog.getSelectRadioButton()));
                        dialog.dismiss();
                    }
                });
                dialog.setNoOnclickListener("取消", new SetRemindTimeDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;
            case R.id.carsystem_cancel_remind:
                final KuaituDialog kuaituDialog = new KuaituDialog(this);
                kuaituDialog.setTitle(getString(R.string.dialogTitle));
                kuaituDialog.setMessage("确定要取消全部网点提醒吗?");
                kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        kuaituDialog.dismiss();
                        requestCancelRemind();
                    }
                });
                kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        kuaituDialog.dismiss();
                    }
                });
                kuaituDialog.show();
                break;
        }
    }

    //用户选中了多少个网点
    private int getSelectedCount() {
        if (remindParkList == null || remindParkList.size() <= 0) {
            return 0;
        }
        int count = 0;
        for (GetRemindBean.Attachment.RemindPark remindPark : remindParkList) {
            if (remindPark.getRemindStatus() == 1) {
                count++;
            }
        }
        return count;
    }

    //用户选中的网点id
    private String getSelectedParkIds() {
        String parkids = "";
        for (GetRemindBean.Attachment.RemindPark remindPark : remindParkList) {
            if (remindPark.getRemindStatus() == 1) {
                parkids += remindPark.getParkId() + ",";
            }
        }
        parkids = parkids.substring(0, parkids.length() - 1);
        return parkids;
    }

    private boolean isAllSelected() {
        boolean selected = true;
        for (int i = 0; i < remindParkList.size(); i++) {
            if (remindParkList.get(i).getRemindStatus() == 0) {
                selected = false;
            }
        }
        return selected;
    }

    public class ListViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return remindParkList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = View.inflate(CarNetSystemActivity.this, R.layout.item_listview_carsystem, null);
            ImageView ivCheckBox = (ImageView) view.findViewById(R.id.carsystem_checkbox);
            TextView tvName = (TextView) view.findViewById(R.id.carsystem_name);
            TextView tvDistance = (TextView) view.findViewById(R.id.carsystem_distance);
            TextView tvAdress = (TextView) view.findViewById(R.id.carsystem_address);
            final GetRemindBean.Attachment.RemindPark remindPark = remindParkList.get(position);
            tvName.setText(remindPark.getParkName());
            tvDistance.setText(remindPark.getDistance());
            tvAdress.setText(remindPark.getAddress());

            if (remindPark.getRemindStatus() == 1) {
                ivCheckBox.setImageResource(R.drawable.item_selected);
            } else {
                ivCheckBox.setImageResource(R.drawable.item_unselected);
            }

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (remindPark.getRemindStatus() == 1) {
                        remindPark.setRemindStatus(0);
                        //tvSelectAll.setText("全选");
                    } else {
                        if (getSelectedCount() >= 3) {
                            ToastCompat.makeText(CarNetSystemActivity.this, "最多可设置3个网点", Toast.LENGTH_SHORT).show();
                        } else {
                            remindPark.setRemindStatus(1);
                        }
                    }
                    notifyDataSetChanged();
                }
            });
            return view;
        }
    }
}
